package com.polaris.live.ui.party.utils

import android.content.Context
import androidx.core.view.isVisible
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.event.EventMessage
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.requestNoCheck
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.dialog_fragment.GiftDialogFragment
import com.polaris.live.im.sfs.bean.live.LiveRoomInfo
import com.polaris.live.im.sfs.bean.live.ext.UserBasicVo
import com.polaris.live.net.liveService
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.bean.GiftSendBean
import com.polaris.live.resp.go_resp.SendPartyGiftBean
import com.polaris.live.translation.R.string
import com.polaris.live.ui.party.widget.seat.bean.BaseSeatBean
import com.polaris.live.utils.BitwiseUtils
import com.polaris.live.utils.fragment.FragmentUtils
import com.polaris.live.widget.circle.CircleCountDownView
import org.greenrobot.eventbus.EventBus

/**
 * 派对房  游戏房   礼物弹出逻辑代理
 *
 * @author Created by 半仙 on 2024/3/4/004 16:18
 */
class GiftDialogProxy(
    private val context: Context,
    private val mViewModel: BaseViewModel,
    private val mLiveInfo: LiveRoomInfo,
    private val mCircle: CircleCountDownView,
    private val isGame: Boolean,
) {

    private var mLastGiftData: SendPartyGiftBean? = null
    private var giftSendBean: GiftSendBean? = null

    private val mGiftDialog by lazy {
        GiftDialogFragment(
            if (isGame) AppConst.GiftComming.GAME else AppConst.GiftComming.PARTY,
            if (isGame) AppConst.BackpackGiftComming.PARTY_GAME else AppConst.BackpackGiftComming.PARTY,
            mLiveInfo.userId,
            true,
            onShowProfileClick = {
                onUserProfileOnClickListener?.invoke(it.userId)
            },
            partySendGiftCallback = { giftSendBean, userList ->
                if (userList.isNotEmpty()) {
                    this.giftSendBean = giftSendBean
                    val sendGiftBean =
                        SendPartyGiftBean(
                            userList,
                            giftSendBean.gift.id,
                            giftSendBean.num,
                            giftSendBean.gift.sourceType,
                            mLiveInfo.liveId,
                            giftSendBean.gift.type,
                            giftSendBean.backpackId,
                            giftSendBean.gift.payload
                        )
                    sendGift(sendGiftBean, giftSendBean.gift.pic)
                } else {
                    ToastGravity.showGravity(StringUtils.getString(string.please_send_gift_user))
                }
            }
        )
    }

    init {
        //连点按钮
        mCircle.setOnClickListener {
            if (!mCircle.isVisible) return@setOnClickListener
            mCircle.anewRun()
            mLastGiftData?.let {
                sendGift(it)
                if (it.backpackId != null) {
                    mGiftDialog.upBackpackIdCount(it.backpackId, -1)
                }
            }
        }
    }

    /**
     * 赠送礼物
     */
    private fun sendGift(sendGiftBean: SendPartyGiftBean, giftPic: String? = null) {
        mViewModel.requestNoCheck({ liveService.batchSend(sendGiftBean) }, {
            if (it.code != 200) {
                ToastGravity.showGravity(it.errorMessage)
                if (it.code == CommonConst.ErrorCode.SENDGIFT) {
                    GlobalPopupManager.showRechargePopup(
                        context,
                        mViewModel,
                        isNeedBottom = true, onRechargeOk = {
                            EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
                        })
                }
                if (it.code == CommonConst.ErrorCode.GAME_BEANS) {
                    GlobalPopupManager.showExchangeGamePopup(context, mViewModel)
                }
                if (it.code == CommonConst.ErrorCode.VIP_LEVEL_INSUFFICIENT) {
                    GlobalDialogManager.showInsufficientVIPLevel(context, sendGiftBean.payload, giftPic)
                }
            } else {
                if (sendGiftBean.backpackId != null) {
                    val amount =
                        (it.ext?.get("backpackAccount") as? Map<String, Any>)?.get("amount")?.toString()
                            ?.toDoubleOrNull()?.toLong()
                    if (amount != null) {
                        mGiftDialog.upBackpackIdAllCount(sendGiftBean.backpackId, amount)
                    }

                }
                if (sendGiftBean.backpackId == null) {
                    if (mGiftDialog.isOnShow() != true) {
                        mCircle.showView()
                    }
                } else {
                    //是选择全部不显示连送
                    if (giftSendBean?.isAll == true) {
                        return@requestNoCheck
                    }

                    val isLuck = BitwiseUtils.isBitwise(sendGiftBean.type, LiveConst.LUCKY_GIFTS.toInt())
                    val isBackLuck = BitwiseUtils.isBitwise(sendGiftBean.type, LiveConst.LUCKY_BACKPACK_GIFT.toInt())
                    if (isLuck || isBackLuck) { //幸运礼物  和  背包幸运礼物有连送
                        if (mGiftDialog.isOnShow() != true) {
                            mCircle.showView()
                        }
                    }
                }

                mLastGiftData = sendGiftBean
            }
        }, {

        })
    }

    /**
     * 展示礼物列表 选中指定礼物
     */
    fun showGiftPopup(
        infoOther: UserBasicVo? = null,
        giftId: Long,
    ) {
        mCircle.viewGone()
        val fragmentManager = FragmentUtils.getFragmentManager(context)
        mGiftDialog.apply {
            if (fragmentManager != null) {
                if (infoOther != null) {
                    setUserId(infoOther.userId, infoOther.nickname)
                    setAvatar(infoOther.avatar, infoOther.avatarFrame)
                    setPartySomeOne(infoOther)
                    setSelectedGiftId(giftId)
                }
                show(fragmentManager, GiftDialogFragment.FRAGMENT_TAG)
            }
        }
    }

    /**
     * 展示礼物列表
     */
    fun showGiftPopup(
        infoOther: UserBasicVo? = null,
        seatList: List<BaseSeatBean>? = null,
        giftType: Int? = null,
    ) {
        mCircle.viewGone()
        val fragmentManager = FragmentUtils.getFragmentManager(context)
        mGiftDialog.apply {
            if (fragmentManager != null) {
                if (!seatList.isNullOrEmpty()) {
                    setPartyAll(seatList, mLiveInfo.userId)
                }
                if (infoOther != null) {
                    setUserId(infoOther.userId, infoOther.nickname)
                    setAvatar(infoOther.avatar, infoOther.avatarFrame)
                    setPartySomeOne(infoOther)
                }
                giftType?.let {
                    setSelectedGiftType(it)
                }
                show(fragmentManager, GiftDialogFragment.FRAGMENT_TAG)
            }
        }
    }

    //查看用户资料回调
    private var onUserProfileOnClickListener: ((otherId: Long) -> Unit)? = null
    fun setOnUserProfileClickListener(click: (otherId: Long) -> Unit) {
        onUserProfileOnClickListener = click
    }

    fun reset() {
        mCircle.viewGone()
    }

}